//
//  AlarmController.swift
//  YOKO
//
//  Created by Zoe_G on 16/5/30.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import Foundation
import UIKit

class AlarmController {
    
    static let app = UIApplication.sharedApplication()
    
    static let notificationQueue = dispatch_get_global_queue(0, 0)
    
    static let helper = AlarmHelper.init()
    
    static func setNotificationWithDateAndTitle(date: NSDate, title: NSString, ID: NSString){
        
        let alarm = UILocalNotification()
        alarm.fireDate = date
        alarm.alertBody = title as String
        alarm.timeZone = NSTimeZone.systemTimeZone()
        alarm.applicationIconBadgeNumber += 1
        alarm.soundName = UILocalNotificationDefaultSoundName
        
        alarm.userInfo = ["identifier": ID, "body": title, "fireDate": date]
        
        app.scheduleLocalNotification(alarm)
        
    }

    static func notificationFirstSet(fireDates: [NSDate], event: Event){
        //先判断是否全天事件
        if event.wholeDayEvent{
            //如果时间内有相应的提醒，则放弃添加数据库
            for fireDate in fireDates{
                let results = helper.findByFiredate(fireDate)
                if results != nil && !(results?.isEmpty)!{
                    for alarm in results!{
                        if alarm.isWholeDay{
                            alarm.wholeDayAlarmCount += 1
                            return
                        }
                    }
                }
                
            }
        }
        
        let now = NSDate()
        let sixHour = NSDate(timeInterval: 6*60*60, sinceDate: NSDate())
        for i in 0...fireDates.count-1{
            //提醒时间小于当前时间
            if fireDates[i].laterDate(now).isEqualToDate(now){
                break
            }
                //提醒时间在6小时之内
            else if(fireDates[i].laterDate(sixHour).isEqualToDate(sixHour)){
                let alarm = Alarm()
                alarm.eventId = String(format: "%i",event.localId)
                if event.wholeDayEvent{
                    alarm.eventTitle = "全天事件"
                }else{
                    alarm.eventTitle = event.summary
                }
                alarm.isSetted = true
                alarm.fireDate = fireDates[i]
                
                alarm.alarmId = String(format: "%i",event.localId) + String(format: "%i",i)
                
                
                self.setNotificationWithDateAndTitle(fireDates[i], title: event.summary, ID: alarm.alarmId!)
            }
            else {
                let alarm = Alarm()
                alarm.eventId = String(format: "%i",event.localId)
                if event.wholeDayEvent{
                    alarm.eventTitle = "全天事件"
                }else{
                    alarm.eventTitle = event.summary
                }
                alarm.isSetted = false
                alarm.fireDate = fireDates[i]
                
                alarm.alarmId = String(format: "%i",event.localId) + String(format: "%i",i)
                
//                dispatch_async(notificationQueue, {
                    helper.add(alarm)
//                })
                
            }
        }
        
    }
    
    static func deleteAlarmWithEvent(fireDates: [NSDate], wholeDayEvent eventWholeDay: Bool, localId eventLocalID: Int){
        //先判断是否全天事件
        if eventWholeDay {
            if let results = helper.findByFiredate(fireDates[0]) {
                for alarm in results{
                    if alarm.isWholeDay {
                        alarm.wholeDayAlarmCount -= 1
                        if alarm.wholeDayAlarmCount==0{
                            if alarm.isSetted{
                                //TODO
                                for notification in app.scheduledLocalNotifications! {
                                    let identifier = notification.userInfo!["identifier"] as! NSString
                                    if alarm.alarmId == identifier {
                                        app.cancelLocalNotification(notification)
                                    }
                                }
                            }else{
//                                dispatch_async(notificationQueue, {
                                    helper.deleteAlarm(alarm)
//                                })
                            }
                        }
                    }
                }
            }
            
        }else{
            //找以前存下的提醒
            if let results = helper.findByEventId(String(formt: "%i", eventLocalID)){
                for alarm in results{
                    
                    if alarm.isSetted{
                        //取消已经注册了的notification
                        for notification in app.scheduledLocalNotifications! {
                            let identifier = notification.userInfo!["identifier"] as! String
                            if alarm.alarmId == identifier {
                                app.cancelLocalNotification(notification)
                            }
                        }
                    }else{
                        //未注册的全部删掉
//                        dispatch_async(notificationQueue, {
                            helper.deleteAlarm(alarm)
//                        })
                    }
                }
            }
        }
    }

    static func updateAlarmWithEvent(fireDates: [NSDate], event: Event){
        //删除已存的
        deleteAlarmWithEvent( fireDates, wholeDayEvent: event.wholeDayEvent, localId: event.localId)
        
        //将新一波提醒存好
        notificationFirstSet(fireDates, event: event)
        
    }
    
    static func updateNotificationBeforeBack(){
//        dispatch_async(notificationQueue, {
            let now = NSDate()
            let aWeek = NSDate(timeInterval: 7*24*60*60, sinceDate: NSDate())
            //取消已经过时的notify
            if let notifies = app.scheduledLocalNotifications{
                for noti in notifies{
//                    print("updateNotificationBeforeBack========\(noti)")
                    //当前时间之前的notify
                    if let later = noti.fireDate?.laterDate(now){
                        if later.isEqualToDate(now){
                            app.cancelLocalNotification(noti)
                        }
                        
                    }
                }
            }
            //数据库查找一周内的提醒
            if let results = helper.findByBeforedate(aWeek){
                if !results.isEmpty{
                    for alarm in results {
                        
                        if let later = alarm.fireDate?.laterDate(now){
                            //过时的提醒删除
                            if later.isEqualToDate(now){
                                
                                helper.deleteByEventId(alarm.eventId)
                            }
                                //未过时的加入notify
                            else{
                                if app.scheduledLocalNotifications?.count < 50
                                {
                                    setNotificationWithDateAndTitle(alarm.fireDate!, title: alarm.eventTitle!, ID: alarm.alarmId!)
                                }
                            }
                        }
                    }
                }
            }
            
//        })
        
    }
    
    
    static func updateNotificationFireDate(event: Event) -> [NSDate]?{
        var fireDates = [NSDate]()
        //拿出event.reminder
        let reminder = event.reminders
        if  reminder != "" {
            let reminderInt = Int(reminder)
            if reminderInt != 0  {
                for i in 0...7{
                    if Bool((1 << i) & reminderInt!){
                        let alarmDate = AlarmController.setNotificationWithTag(i, beginDate: event.timeBegin)
                        fireDates.append(alarmDate)
                    }
                    
                }
            }
        }
        return fireDates
    }
    
    // ["事件发生时","5分钟前","15分钟前","30分钟前","1小时前","1天前","2天前","一周前"]
    static func setNotificationWithTag(i: Int, beginDate: NSDate) -> NSDate {
        switch i {
        case 0:
            return beginDate
        case 1:
            return beginDate.add(0, months: 0, weeks: 0, days: 0, hours: 0, minutes: -5, seconds: 0, nanoseconds: 0)
        case 2:
            return beginDate.add(0, months: 0, weeks: 0, days: 0, hours: 0, minutes: -15, seconds: 0, nanoseconds: 0)
        case 3:
            return beginDate.add(0, months: 0, weeks: 0, days: 0, hours: 0, minutes: -30, seconds: 0, nanoseconds: 0)
        case 4:
            return beginDate.add(0, months: 0, weeks: 0, days: 0, hours: -1, minutes: 0, seconds: 0, nanoseconds: 0)
        case 5:
            return beginDate.add(0, months: 0, weeks: 0, days: -1, hours: 0, minutes: 0, seconds: 0, nanoseconds: 0)
        case 6:
            return beginDate.add(0, months: 0, weeks: 0, days: -2, hours: 0, minutes: 0, seconds: 0, nanoseconds: 0)
        case 7:
            return beginDate.add(0, months: 0, weeks: -1, days: 0, hours: 0, minutes: 0, seconds: 0, nanoseconds: 0)
        default:
            return beginDate
        }
    }


    
}
